package com.hostmanagement.servlet;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author glen
 * 
 */
public class URLDetectServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private String[] names = null;

	private String encoding = null;

	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws IOException, ServletException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		int skipNum = 0;
		String urlStr = null;
		StringBuffer reqURL = request.getRequestURL();

		if (reqURL.indexOf("Servlet") > 0 || reqURL.indexOf(".jsp") > 1) {
			Map map = request.getParameterMap();
			Set keySet = map.keySet();

			StringBuffer url = request.getRequestURL().append("?");

			for (Iterator it = keySet.iterator(); it.hasNext();) {
				String name = it.next().toString();
				String value = request.getParameter(name);

				// Start to filter characters
				if (value != null) {
					boolean bTrim = !value.equals(value.trim());
					if (bTrim) {
						value = value.trim();
						skipNum++;
					}

					StringBuffer tmp = new StringBuffer(value);
					boolean bSkip = false;
					for (int i = 0; i < names.length; i++) {
						if (tmp.toString().indexOf((String) names[i]) != -1) {
							bSkip = true;
							break;
						}
					}

					if (bSkip) {
						value = value.replaceAll("\'", "\"");
					}

					boolean single_quotes = tmp.toString().indexOf("\'") != -1;
					if (single_quotes) {
						for (int i = 0; i < url.length(); i++) {
							if (tmp.charAt(i) == '\'') {
								tmp.replace(i, i + 1, "\"");
							}
						}
						skipNum++;
						value = tmp.toString();
					}

				}

				url.append(name).append("=").append(value).append("&");
			}

			urlStr = url.toString();
			if (skipNum > 0) {
				urlStr = url.toString();
				urlStr = new String(urlStr.getBytes("gb2312"), "ISO8859-1");
			}
		}
		System.out.println("========= urlStr is " + urlStr);
		request.getRequestDispatcher(urlStr);
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

}
